package com.nwpu.bigdata.dao.impl;

import org.influxdb.InfluxDB;


import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.nwpu.bigdata.dao.InfluxdbDao;

import java.util.Map;

/**
 *
 * @author chengar zhanggr
 *
 */
@Repository
public class InfluxdbDaoImpl implements InfluxdbDao {
	
	@Autowired
	private InfluxDB influxDB;

	private String database;
    private String policyName;

    /* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#createDatabase()
	 */
    @Override
	public void createDatabase(){
        influxDB.createDatabase(database);
    }

    /* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#createRetentionPolicy(java.lang.String, java.lang.Integer)
	 */
    @Override
	public void createRetentionPolicy(String duration, Integer replicationNum){
        String cmd = String.format("CREATE RETENTION POLICY %s ON %s DURATION %s REPLICATION %s DEFAULT",
        													policyName,database,duration,replicationNum); //数据保存策略
        influxDB.query(new Query(cmd,database));
    }


    /* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#query(java.lang.String)
	 */
    @Override
	public QueryResult query(String cmd){
        return influxDB.query(new Query(cmd,database));
    }

    /* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#insert(java.lang.String, java.util.Map, java.util.Map)
	 */
    @Override
	public void insert(String measurement,Map<String,String> tags,Map<String,Object> fields){
        Point.Builder builder = Point.measurement(measurement).tag(tags);
        if(fields != null && !fields.isEmpty()){
            builder.fields(fields);
        }
        influxDB.write(database,policyName,builder.build());
    }

    /* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#getDatabase()
	 */
    @Override
	public String getDatabase() {
        return database;
    }

    /* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#getPolicyName()
	 */
    @Override
	public String getPolicyName() {
        return policyName;
    }

    /* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#getInfluxDB()
	 */
    @Override
	public InfluxDB getInfluxDB() {
        return influxDB;
    }

	/* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#setDatabase(java.lang.String)
	 */
	@Override
	public void setDatabase(String database) {
		this.database = database;
	}

	/* (non-Javadoc)
	 * @see com.nwpu.bigdata.dao.impl.InfluxdbDao#setPolicyName(java.lang.String)
	 */
	@Override
	public void setPolicyName(String policyName) {
		this.policyName = policyName;
	}
}